如何将 ASCII 码转换为字符 您所在的位置:网站首页 java 字符ascii 如何将 ASCII 码转换为字符

如何将 ASCII 码转换为字符

2024-06-29 19:39| 来源: 网络整理| 查看: 265

在 Java 中使用强制转换将 ASCII 码转换为 Char 码 在 Java 中使用 Character.toString 将 ASCII 码转换为字符 在 Java 中使用 Character.toString 转换 ASCII 码为字符 在 Java 中使用 Character.toChars() 转换 ASCII 码为字符

本文讨论了如何使用 Java 中的方法将一个 ASCII 码转换为字符。此外,我们还演示了如何将大写字母转换成小写字母,反之亦然。

在 Java 中使用强制转换将 ASCII 码转换为 Char 码

从 ASCII 码中提取字符的最基本也是最简单的方法是直接将 ASCII 码强制转换为字符,这将把 int 类型的 asciiValue 转换为 char 类型。

public class Main { public static void main(String[] args) { int asciiValue = 97; char convertedChar = (char) asciiValue; System.out.println(convertedChar); } }

输出:

a 在 Java 中使用 Character.toString 将 ASCII 码转换为字符

Java 的字符类为我们提供了一个 toString() 方法,该方法在 codePoint 中转换为一个字符;在本例中,我们有一个 ASCII 码。我们可以把转换方法放入一个循环中,得到所有的大写英文字母。注意,循环从 65 到 90,这就是大写字母对应的 ASCII 码。

这个方法与我们上面使用的例子相比,好处是如果 int 值没有被正确验证,它可以抛出一个异常。

public class Main { public static void main(String[] args) { int asciiValue = 65; for (int i = asciiValue; i 97 => a 98 => b 99 => c 100 => d 101 => e 102 => f 103 => g 104 => h 105 => i 106 => j 107 => k 108 => l 109 => m 110 => n 111 => o 112 => p 113 => q 114 => r 115 => s 116 => t 117 => u 118 => v 119 => w 120 => x 121 => y 122 => z 在 Java 中使用 Character.toChars() 转换 ASCII 码为字符

我们可以使用 Java 中字符类的另一个方法,即 toChars;它接收一个类似 ASCII 值的 CodePoint,并返回一个 char 数组。

public class Main { public static void main(String[] args) { int asciiValue = 255; char[] convertedCharArray = Character.toChars(asciiValue); System.out.println(convertedCharArray); } }

输出:

ÿ


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有